<template>
  <div>
    <el-drawer
      direction="ttb"
      :visible.sync="insertVisibility"
      :with-header="false"
      size="84%"
    >
      <el-form
        ref="outStockBill"
        class="outStockBill"
        :model="outStockBill"
        :rules="rules"
        size="mini"
        label-width="auto"
        inline
      >
        <el-divider>BILL-SUMMARY</el-divider>
        <el-row :gutter="36">
          <el-col :span="12">
            <el-form-item prop="storeHouse" label="仓库：">
              <el-input v-model.trim="outStockBill.storeHouse"> </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item prop="outStockTime" label="领用时间：">
              <el-date-picker v-model="outStockBill.outStockTime">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="36">
          <el-col :span="12">
            <el-form-item prop="applier" label="领用人：">
              <el-input v-model.trim="outStockBill.applier"> </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="申请部门：">
              <el-select v-model="outStockBill.applyDepartment">
                <el-option
                  v-for="e in this.$store.state.departments"
                  :key="e.index"
                  :value="e.value"
                  :label="e.text"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider>MATERIAL-DETAIL</el-divider>

        <div class="space-flex">
          <el-button type="primary" size="mini" @click="delDetail"
            >删除</el-button
          >
          <el-button type="primary" size="mini" @click="addDetail"
            >添加</el-button
          >
        </div>
        <el-table
          ref="outStockMaterialDetails"
          :data="outStockBill.outStockMaterialDetails"
          max-height="300px"
          border
          show-summary
          :summary-method="summaryMethod"
          @selection-change="selectionChange"
        >
          <!--       { //自然流水号No 1 2 3
            outStockMaterialDetailId: {
              detailNo: 0,},
            //编号
            materialCode: "string",
            //冗余字段名称 价格可以以参考价格为初始值
            materialName: "string",
            unit: "string",
            //手动调整和填写
            unitPrice: 0,
            quantity: 0,
            //计算属性
            amount: 0,
          },      -->
          <el-table-column
            type="index"
            align="center"
            label="--"
          ></el-table-column>
          <el-table-column type="selection" align="center"></el-table-column>

          <el-table-column align="left" width="228" label="编号">
            <template #default="{ row }">
              <el-link type="success" icon="el-icon-s-goods">{{
                row.materialCode
              }}</el-link>
            </template>
          </el-table-column>
          <el-table-column
            prop="materialName"
            label="品名"
            width="150"
          ></el-table-column>
          <el-table-column
            prop="unit"
            label="单位"
            width="50"
          ></el-table-column>
          <el-table-column prop="unitPrice" label="单价" width="150">
            <template #default="{ row }">
              <el-form-item>
                <el-input-number
                  v-model="row.unitPrice"
                  :precision="2"
                ></el-input-number>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column sortable width="150" prop="quantity" label="数量">
            <template #default="{ row }">
              <el-form-item>
                <el-input-number
                  precision="0"
                  type="number"
                  size="mini"
                  v-model="row.quantity"
                ></el-input-number>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            sortable
            width="100"
            prop="amount"
            label="小计"
          >
            <template #default="{ row }">
              <span>{{ amountC(row) }}</span>
            </template>
          </el-table-column>
        </el-table>
        <el-row>
          <el-col :span="24">
            <el-form-item>
              <el-input
                v-model="outStockBill.comment"
                placeholder="备注信息"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider>OPERATOR-SIGN</el-divider>
        <el-descriptions border size="medium" column="2">
          <el-descriptions-item label="申请人">
            <el-tag>{{
              $store.state.userInfo.username || "匿名用户"
            }}</el-tag></el-descriptions-item
          >
          <el-descriptions-item label="审核人">--</el-descriptions-item>
        </el-descriptions>

        <div class="space-flex">
          <el-button type="warning" icon="el-icon-remove" @click="reset"
            >重置
          </el-button>
          <el-button
            type="primary"
            icon="el-icon-edit"
            @click="outStockBillSubmit"
            >提交
          </el-button>
        </div>
      </el-form>
    </el-drawer>
    <out-stock-refer-material
      ref="outStockReferMaterial"
      @post-supported="postSupported"
    ></out-stock-refer-material>
  </div>
</template>

<script>
import OutStockReferMaterial from "@/components/erp/OutStockReferMaterial";
/**
 * 页面核心数据结构体说明文档
 *  outStockBill: {
        //前端确定 申请人 申请部门 申请时间 申请仓库  备注
        applyDepartment: "tech",
        applier: "string",
        outStockTime: "2022-02-20T09:33:30.124Z",
        storeHouse: "string",
        comment: "string",
        // 后端确定一  核心流程相关字段
        billOperator: "string",
        operateState: "notSubmit",
        billAuditor: "string",
        auditState: "NA",
        // 后端确定二 技术相关和计算属性等
        outStockCode: "string",
        totalAmount: 0,
        abandoned: true,
        version: 0,
        // 一对多 详情
        outStockMaterialDetails: [
          {
            //自然流水号No 1 2 3
            outStockMaterialDetailId: {
              detailNo: 0,
            },
            //编号
            materialCode: "string",
            //冗余字段名称 价格可以以参考价格为初始值
            materialName: "string",
            unit: "string",

            //手动调整和填写
            unitPrice: 0,
            quantity: 0,

            //计算属性
            amount: 0,


          },
        ],
      },
 *
 * outStockMaterialDetails中的详情参考 Material表
 *  注意信息对接 如  description <=> materialName
 *     {
      "materialCode": "MM001001060089",
      "description": "万向轮",
      "barCode": "112255",
      "specification": "半径20cm重量2.5kg",
      "referPrice": 125.5,
      "chargeUnit": "个",
      "producingArea": "Zhejiang",
      "abandoned": false
    },
 *
 */
// import New from './components/New.vue';
export default {
  name: "OutStockInsert",
  components: {
    OutStockReferMaterial,
    // New,Old,
  },
  props: {
    sampleP: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {
      insertVisibility: false,
      outStockBill: {
        //前端确定 申请人 申请部门 申请时间 申请仓库  备注
        applyDepartment: "tech",
        applier: "zhangsan",
        outStockTime: new Date().toJSON(),
        storeHouse: "北仓11-10",
        comment: "请提前准备",
        // 后端确定一  核心流程相关字段
        billOperator: null,
        operateState: null,
        billAuditor: null,
        auditState: null,
        // 后端确定二 技术相关和计算属性等
        outStockCode: null,
        totalAmount: 0,
        abandoned: false,
        version: 0,

        outStockMaterialDetails: [],
      },
      selectedDetails: [],
      /*   rules: {
        username: [
          { required: true, message: "请输入账号", trigger: "blur" },
          {
            pattern: /^\w+$/,
            message: "请输入字母/数字/下划线",
            trigger: ["blur", "change"],
          },
          { validator: this.validateItem, trigger: "blur" },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },*/
      rules: {
        applier: [{ required: true, message: "请输入领用人", trigger: "blur" }],
      },
    };
  },
  computed: {
    // sampleC() {
    //     return this.sampleD+'--';
    // }
    amountC() {
      return function (row) {
        row.amount = row.unitPrice * row.quantity;

        return row.amount;
      };
    },
    // amountc(row)()
  },
  created() {},
  mounted() {},
  methods: {
    sampleM() {},
    appear() {
      this.insertVisibility = !this.insertVisibility;
    },
    addDetail() {
      this.$refs.outStockReferMaterial.appear();
    },
    delDetail() {
      let t = this.outStockBill.outStockMaterialDetails.filter((x) => {
        let p = this.selectedDetails.find((y) => {
          return (
            y.outStockMaterialDetailId.detailNo ===
            x.outStockMaterialDetailId.detailNo
          );
        });
        return !p;
      });

      this.outStockBill.outStockMaterialDetails = t;
    },
    /**
        * {
      "materialCode": "MM001001060089",
      "description": "万向轮",
      "barCode": "112255",
      "specification": "半径20cm重量2.5kg",
      "referPrice": 125.5,
      "chargeUnit": "个",
      "producingArea": "Zhejiang",
      "abandoned": false
    },
          to
          {
            amount: 0,
            materialCode: "string",
            materialName: "string",
            outStockMaterialDetailId: {
              detailNo: 0,
            },
            quantity: 0,
            unit: "string",
            unitPrice: 0,
          },
        * */

    postSupported(supported) {
      // this.$message.warning("Debug supported :" + JSON.stringify(supported));
      let detail = supported.map((x) => {
        return {
          //自然流水号No 1 2 3
          outStockMaterialDetailId: {
            detailNo: Math.floor(Math.random() * 100),
          },
          //编号
          materialCode: x.materialCode,
          //冗余字段名称 价格可以以参考价格为初始值
          materialName: x.description,
          unit: x.chargeUnit,

          //手动调整和填写
          unitPrice: x.referPrice,
          quantity: 1,

          //计算属性
          amount: 0,
        };
      });

      this.outStockBill.outStockMaterialDetails.push(...detail);
      // this.$notify.warning("Debug this.outStockBill.outStockMaterialDetails :"+JSON.stringify(this.outStockBill.outStockMaterialDetails));
    },

    summaryMethod({ columns, data }) {
      //column对象是 el-table-column代表的元信息列 如prop属性property 如align left 等
      //columns 为 List<column>
      //detailsData 为 form内嵌table 中table绑定的data 其中元素依然建议用row的概念表示 理解好 row[column.property]
      const sums = [];
      // console.log(" ---- "+columns.length)
      columns.forEach((column, index) => {
        //index 从0开始到n 以此循环 是行数
        const values = data.map((row) => Number(row[column.property]));
        /**
         *
         * 一般范式 最后一列作为统计列*/
        // console.log(columns.length - 1);
        if (index === columns.length - 1) {
          if (values.length) {
            sums[index] = values.reduce((a0, ai) => {
              if (!isNaN(ai)) {
                return a0 + ai;
              } else {
                //如果不是数字 就略过
                return a0 + 0;
              }
            });
          } else {
            sums[index] = 0;
          }
        }
        //
        if (index === 0) {
          sums[index] = "小";
        }
        if (index === 1) {
          sums[index] = "计";
        }
      });
      return sums;
    },
    selectionChange(selected) {
      this.selectedDetails = selected;
    },

    formatReq(outStockBill) {
      let d = outStockBill.outStockMaterialDetails;
      for (let i = 0; i < d.length; i++) {
        d[i].outStockMaterialDetailId.detailNo = i + 1;
      }
      // this.$notify.warning(
      //   "Debug outStockBill :" + JSON.stringify(outStockBill)
      // );
      return outStockBill;
    },
    outStockBillSubmit() {
      this.$refs.outStockBill.validate((valid) => {
        if (valid) {
          let req = this.formatReq(this.outStockBill);
          this.$http({
            method: "post",
            url: "http://127.0.0.1:9092/erp/outStock/insert",
            data: req,
          }).then(
            (res) => {
              this.$message.warning(JSON.stringify(res.data));
              this.insertVisibility = false;
              this.$nextTick(() => {
                this.$emit("post-insert");
              });
            },
            (error) => {
              console.log(
                ".outStockBill request error : " + error.response.status
              );
            }
          );
        } else {
          this.$message.warning("验证不通过请重新填写表单");
        }
      });
    },
    reset() {},
  },
  watch: {
    // sampleC(newValue, oldValue) {
    //
    // }
  },
};
</script>

<!--<style scoped>-->
<style lang="scss" scoped>
.el-form {
  width: 66%;
  padding-left: 300px;
  .el-select {
    width: 100%;
  }
}
.space-flex {
  display: flex;
  justify-content: space-between;
  padding: 10px 0;
}
/**
el form item 本身长度是被撑开的 margin-button 23px >>> /deep/
*/
.el-table {
  ::v-deep .el-form-item {
    margin-bottom: 0;

    .el-form-item__content {
      margin-left: 0 !important;
    }
  }
}
/*
默认padding 13px 缩小 行间距
*/
.el-table {
  ::v-deep .el-table__cell {
    padding: 4px 0;
  }
}
.el-divider {
  margin: 8px 0;
}
</style>
